<template>
  <div>
    <el-form :inline="true" :model="userViewData.productQueryParam">
      <el-form-item label="商品名称">
        <el-input
          @blur="search"
          v-model="userViewData.productQueryParam.productName"
          placeholder="请输入商品名称"
        />
      </el-form-item>
      <el-form-item label="商品类别">
        <el-select
          v-model="userViewData.productQueryParam.categoryId"
          @change="search"
          placeholder="请选择商品类别"
        >
          <el-option :key="0" label="全部" :value="0" />
          <el-option
            v-for="item in userViewData.categorylist"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="上架状态">
        <el-select
          v-model="userViewData.productQueryParam.onShelf"
          @change="search"
          placeholder="请选择上架状态"
        >
          <el-option :key="-1" label="全部" :value="-1" />
          <el-option
            v-for="item in userViewData.shelfState"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="search()">
          查 询
        </el-button>
        <el-button type="primary" :icon="Refresh" @click="refresh()">
          重 置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 表格数据 -->
    <el-table :data="userViewData.tableData" border style="width: 100%">
      <el-table-column prop="productId" label="商品Id" align="center" />
      <el-table-column prop="imageUrls" label="图集" align="center">
        <template #default="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.img">
            <template #placeholder>
              <div class="image-slot">
                图片加载中<span class="dot">...</span>
              </div>
            </template>
            <template #error>
              <div class="image-slot">暂无图片</div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="productName"
        label="商品名称"
        align="center"
        width="500"
      />
      <el-table-column prop="categoryName" label="类别" align="center" />
      <el-table-column prop="price" label="价格" align="center" />
      <el-table-column prop="stock" label="库存" align="center" />
      <el-table-column prop="saleCount" label="销量" align="center" />
      <el-table-column prop="onShelf" label="上架状态" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.onShelf === 0" class="ml-2" type="info">
            已下架
          </el-tag>
          <el-tag
            v-else-if="scope.row.onShelf === 1"
            class="ml-2"
            type="success"
          >
            上架中
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <div class="flex j-s a-c">
            <el-button
              @click="viewDetail(scope.row.productId)"
              type="primary"
              link
            >
              查看详情
            </el-button>
            <el-button
              @click="deleteProduct(scope.row.productId)"
              type="danger"
              link
            >
              删除
            </el-button>
            <!-- 上架 和 下架 需要和 当前状态相反-->
            <el-button
              type="primary"
              @click="onShelf(scope.row.productId, 1)"
              link
              v-if="scope.row.onShelf === 0"
            >
              上架
            </el-button>
            <el-button
              type="primary"
              @click="onShelf(scope.row.productId, 0)"
              link
              v-if="scope.row.onShelf === 1"
            >
              下架
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="mt-4 pagination"
      background
      layout="prev, pager, next"
      @current-change="currentChange"
      :page-size="userViewData.page.size"
      :total="userViewData.page.total"
    />

    <!-- 查看详情-->
    <el-dialog
      v-model="userViewData.edit.show"
      :title="userViewData.edit.title"
      width="60%"
    >
      <el-form ref="form" :model="userViewData.edit.list" label-width="80px">
        <el-form-item label="图片">
          <el-image
            v-for="item in userViewData.edit.list.imgUrl"
            style="width: 100px; height: 100px"
            :src="item"
            :preview-src-list="userViewData.edit.list.imgUrl"
            :initial-index="0"
            fit="cover"
          />
        </el-form-item>
        <el-form-item label="类别">
          <el-input disabled v-model="userViewData.edit.list.categoryName" />
        </el-form-item>
        <el-form-item label="状态">
          <el-tag
            v-if="userViewData.edit.list.onShelf === 0"
            class="ml-2"
            type="success"
          >
            上架中
          </el-tag>
          <el-tag
            v-else-if="userViewData.edit.list.onShelf === 1"
            class="ml-2"
            type="info"
          >
            已下架
          </el-tag>
        </el-form-item>
        <el-form-item label="价格">
          <el-input disabled v-model="userViewData.edit.list.price" />
        </el-form-item>
        <el-form-item label="销量">
          <el-input disabled v-model="userViewData.edit.list.saleCount" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input disabled v-model="userViewData.edit.list.stock" />
        </el-form-item>
        <el-form-item label="简介">
          <div v-html="userViewData.edit.list.introduction"></div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userViewData.edit.show = false">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Search, Refresh, Picture } from "@element-plus/icons-vue";
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import {
  getProduct,
  getProductById,
  getCategories,
  getCategoriesById,
  editProduct,
  deleteProductById,
} from "@/api/product";
import { ProductQueryParam, UserViewData } from "@/type/product";
import service from "@/request";
import { ElMessage, ElMessageBox } from "element-plus";

const userViewData = reactive(new UserViewData());
// 初始化数据
onMounted(() => {
  getCategoriesList();
  search();
});

// 获取商品类别列表
const getCategoriesList = () => {
  getCategories().then(res => {
    userViewData.categorylist = res.data;
  });
};

// 查询商品，表格数据
const getTableData = data => {
  // 如果上架状态是全部，默认不传
  data.onShelf = data.onShelf === -1 ? undefined : data.onShelf;
  getProduct(data).then(res => {
    // 目的：回显全部字样
    userViewData.productQueryParam.onShelf =
      data.onShelf === undefined ? -1 : data.onShelf;
    res.data.records.forEach(r => {
      r.imgUrl = r.imageUrls ? r.imageUrls.split(",") : [];
      r.img = r.imgUrl[0];
    });
    userViewData.tableData = res.data.records;
    userViewData.page.total = Number(res.data.total);
  });
};

// 上一页 || 下一页
const currentChange = (page: number) => {
  userViewData.productQueryParam.current = page;
  getTableData(userViewData.productQueryParam);
};

// 搜索
const search = () => {
  getTableData(userViewData.productQueryParam);
};

// 重置
const refresh = () => {
  userViewData.productQueryParam = {
    categoryId: 0,
    current: undefined,
    onShelf: -1,
    orders: undefined,
    productName: undefined,
    size: undefined,
    stock: undefined,
  };
  userViewData.tableData = [];
  search();
};

// 查看详情
const viewDetail = e => {
  getProductById(e).then(res => {
    res.data.imgUrl = res.data.imageUrls ? res.data.imageUrls.split(",") : [];
    userViewData.edit.list = res.data;
    userViewData.edit.show = true;
    userViewData.edit.title = res.data.productName;
  });
};

// 上架 还是 下架
const onShelf = (id, e) => {
  let data = {
    productId: id,
    onShelf: e,
  };
  ElMessageBox.confirm(`是否确定${e === 1 ? "上架" : "下架"}此商品？`, {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "warning",
  })
    .then(() => {
      editProduct(data).then(res => {
        if (res.code === 200) {
          ElMessage({
            message: "修改成功",
            type: "success",
          });
          search();
        } else {
          ElMessage({
            message: "修改失败",
            type: "warning",
          });
        }
      });
    })
    .catch(() => {});
};

// 删除
const deleteProduct = e => {
  ElMessageBox.confirm("是否确定删除此商品？", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "warning",
  })
    .then(() => {
      deleteProductById(e).then(res => {
        if (res.code === 200) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          search();
        } else {
          ElMessage({
            message: "删除失败",
            type: "warning",
          });
        }
      });
    })
    .catch(() => {});
};
</script>
<style scoped>
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
</style>
